<template>
  <div class="my-purchase">
    <!-- 顶部导航 -->
    <van-nav-bar
      title="我的求购"
      left-arrow
      @click-left="onClickLeft"
      fixed
      placeholder
      safe-area-inset-top
    >
      <template #right>
        <span class="nav-right" @click="onPublish">发布求购</span>
      </template>
    </van-nav-bar>

    <!-- 标签页 -->
    <div class="tabs-container">
      <van-tabs
        v-model:active="active"
        color="#32BC05"
        line-height="2px"
        @change="onTabChange"
        sticky
      >
        <van-tab :title="'求购中(' + ongoingCount + ')'">
          <div class="scroll-container">
            <van-pull-refresh v-model="ongoingRefreshing" @refresh="onRefresh">
              <van-list
                v-model:loading="ongoingLoading"
                :finished="ongoingFinished"
                finished-text="没有更多了"
                @load="onLoadOngoing"
              >
                <div class="purchase-list">
                  <div class="purchase-item" v-for="(item, index) in ongoingList" :key="index">
                    <div class="item-header">
                      <div class="title">{{ item.title }}</div>
                      <div class="specs">
                        <van-tag
                          plain
                          type="primary"
                          class="spec-tag"
                          round
                          v-if="item.plantAttribute"
                          >{{ item.plantAttribute }}</van-tag
                        >
                      </div>
                      <div class="size">
                        <span v-for="(attr, attrIndex) in item.attributeDocuments" :key="attrIndex"
                          >{{ attr.attributeName }}:{{ attr.minValue }}-{{ attr.maxValue
                          }}{{ attr.unit }}</span
                        >
                      </div>
                      <div class="location">
                        <span class="label">用苗地址：</span>
                        <span class="value">{{
                          `${item.receiveProvince}${item.receiveCity}`
                        }}</span>
                        <span class="date">发布时间：{{ item.createTime.slice(0, 10) }}</span>
                      </div>
                    </div>
                    <div class="item-footer van-hairline--top">
                      <div class="btn" @click="viewDetail(item)">查看详情</div>
                      <div class="btn" @click="stopPurchase(item)">停止求购</div>
                    </div>
                  </div>
                </div>
              </van-list>
            </van-pull-refresh>
          </div>
        </van-tab>
        <van-tab :title="'已结束(' + finishedCount + ')'">
          <div class="scroll-container">
            <van-pull-refresh v-model="finishedRefreshing" @refresh="onRefresh">
              <van-list
                v-model:loading="finishedLoading"
                :finished="finishedFinished"
                finished-text="没有更多了"
                @load="onLoadFinished"
              >
                <div class="purchase-list">
                  <div class="purchase-item" v-for="(item, index) in finishedList" :key="index">
                    <div class="item-header">
                      <div class="title">{{ item.title }}</div>
                      <div class="specs">
                        <van-tag
                          plain
                          type="primary"
                          class="spec-tag"
                          round
                          v-if="item.plantAttribute"
                          >{{ item.plantAttribute }}</van-tag
                        >
                      </div>
                      <div class="size">
                        <span v-for="(attr, attrIndex) in item.attributeDocuments" :key="attrIndex"
                          >{{ attr.attributeName }}:{{ attr.minValue }}-{{ attr.maxValue
                          }}{{ attr.unit }}</span
                        >
                      </div>
                      <div class="location">
                        <span class="label">用苗地址：</span>
                        <span class="value">{{
                          `${item.receiveProvince}${item.receiveCity}`
                        }}</span>
                        <span class="date">发布时间：{{ item.createTime.slice(0, 10) }}</span>
                      </div>
                    </div>
                    <div class="item-footer van-hairline--top">
                      <div class="btn" @click="againPurchase(item)">再次求购</div>
                      <div class="btn" @click="deleteItem(item)">删除</div>
                    </div>
                  </div>
                </div>
              </van-list>
            </van-pull-refresh>
          </div>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { selfQuery, selfStop, selfAgain, batchRemove } from '@/api'
import bridge from '@/utils/bridge'
const router = useRouter()
const active = ref(0)

// 求购中列表相关
const ongoingList = ref([])
const ongoingLoading = ref(false)
const ongoingFinished = ref(false)
const ongoingRefreshing = ref(false)
const ongoingCount = ref(0)

// 已结束列表相关
const finishedList = ref([])
const finishedLoading = ref(false)
const finishedFinished = ref(false)
const finishedRefreshing = ref(false)
const finishedCount = ref(0)

const onGoingParams = ref({
  pageSize: 10,
  pageNum: 1,
  type: 1
})

const onFinishedParams = ref({
  pageSize: 10,
  pageNum: 1,
  type: 2
})

// 加载求购中列表数据
const onLoadOngoing = async () => {
  ongoingLoading.value = true
  try {
    const { code, rows, total } = await selfQuery(onGoingParams.value)
    if (code === 200) {
      ongoingList.value.push(...rows)
      ongoingLoading.value = false
      ongoingCount.value = total
      onGoingParams.value.pageNum++
      if (ongoingList.value.length >= total) {
        ongoingFinished.value = true
      }
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ongoingLoading.value = false
  }
}

// 加载已结束列表数据
const onLoadFinished = async () => {
  finishedLoading.value = true
  try {
    const { code, rows, total } = await selfQuery(onFinishedParams.value)
    if (code === 200) {
      finishedList.value.push(...rows)
      finishedLoading.value = false
      finishedCount.value = total
      onFinishedParams.value.pageNum++
      if (finishedList.value.length >= total) {
        finishedFinished.value = true
      }
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    finishedLoading.value = false
  }
}

// 下拉刷新
const onRefresh = async () => {
  if (active.value === 0) {
    // 刷新求购中列表
    onGoingParams.value.pageNum = 1
    ongoingList.value = []
    ongoingFinished.value = false
    await onLoadOngoing()
    ongoingRefreshing.value = false
  } else {
    // 刷新已结束列表
    onFinishedParams.value.pageNum = 1
    finishedList.value = []
    finishedFinished.value = false
    await onLoadFinished()
    finishedRefreshing.value = false
  }
}

// 标签切换
const onTabChange = (index: number) => {
  if (index === 0 && ongoingList.value.length === 0) {
    onGoingParams.value.pageNum = 1
    onLoadOngoing()
  } else if (index === 1 && finishedList.value.length === 0) {
    onLoadFinished()
    onFinishedParams.value.pageNum = 1
  }
}

const onClickLeft = () => {
  bridge.closeWebView()
}

const onPublish = () => {
  router.push({
    path: '/buySeedings'
  })
}

const viewDetail = (item: any) => {
  router.push({
    path: '/purchaseDetail',
    query: {
      pullProductId: item.id,
      type: '2'
    }
  })
}

const stopPurchase = async (item: any) => {
  showConfirmDialog({
    title: '提示',
    message: '是否确认停止求购'
  })
    .then(async () => {
      let { code, msg } = await selfStop({
        pullProductId: item.id
      })
      if (code === 200) {
        showSuccessToast(msg)
        onGoingParams.value.pageNum = 1
        onLoadOngoing()
      }
    })
    .catch(() => {})
}

const deleteItem = (item: any) => {
  showConfirmDialog({
    title: '提示',
    message: '是否确认删除求购'
  })
    .then(async () => {
      let arr = [item.id]
      console.log(arr)
      let { code, msg } = await batchRemove(arr)
      if (code === 200) {
        showSuccessToast(msg)
        onFinishedParams.value.pageNum = 1
        onLoadFinished()
      }
    })
    .catch(() => {})
}

const againPurchase = (item: any) => {
  showConfirmDialog({
    title: '提示',
    message: '是否确认再次求购'
  })
    .then(async () => {
      let { code, msg } = await selfAgain({
        pullProductId: item.id
      })
      if (code === 200) {
        showSuccessToast(msg)
        onFinishedParams.value.pageNum = 1
        onLoadFinished()
      }
    })
    .catch(() => {})
}

// 初始加载
onMounted(() => {
  // 隐藏原生导航
  bridge.setNavigationBarVisible({
    value: '0'
  })
  onGoingParams.value.pageNum = 1
  onFinishedParams.value.pageNum = 1
  onLoadOngoing()
  onLoadFinished()
})
</script>

<style lang="scss" scoped>
.my-purchase {
  min-height: 100vh;
  background: #f7f8fa;
  display: flex;
  flex-direction: column;

  :deep(.van-nav-bar) {
    background: #fff;
    &::after {
      border: none;
    }

    .van-nav-bar__title {
      color: #222;
      font-weight: 400;
      font-size: 17px;
    }

    .van-icon {
      color: #222;
    }
  }

  .nav-right {
    color: #32bc05;
    font-size: 14px;
  }

  .tabs-container {
    flex: 1;
    display: flex;
    flex-direction: column;

    :deep(.van-tabs) {
      display: flex;
      flex-direction: column;
      height: 100%;

      .van-tabs__wrap {
        flex-shrink: 0;
      }

      .van-tabs__content {
        flex: 1;
        overflow: hidden;
      }

      .van-tab__pane {
        height: 100%;
      }
    }
  }

  .scroll-container {
    height: calc(100vh - 90px); // 减去导航栏和标签栏的高度
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
  }

  :deep(.van-tab) {
    font-size: 14px;
    font-weight: 400;
  }

  :deep(.van-tab--active) {
    color: #32bc05;
    font-weight: 400;
  }

  .purchase-list {
    padding: 10px;
  }

  .purchase-item {
    background: #fff;
    border-radius: 8px;
    margin-bottom: 12px;

    .item-header {
      padding: 12px;

      .title {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        font-size: 15px;
        color: #222;
      }

      .specs {
        margin-bottom: 8px;

        .spec-tag {
          margin-right: 8px;
          font-size: 12px;
          color: #32bc05;
          background: #fff;
          border-color: #32bc05;
          font-size: 10px;
        }
      }

      .size {
        font-size: 14px;
        color: #222;
        margin-bottom: 8px;
        width: 100%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        span {
          margin-right: 8px;
        }
      }

      .location {
        font-size: 11px;
        display: flex;
        color: #999;
        justify-content: space-between;

        .value {
          margin-right: 10px;
          flex: 1;
          width: 100%;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }

    .item-footer {
      display: flex;
      height: 44px;

      .btn {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        color: #222;

        &:first-child {
          border-right: 1px solid #eee;
        }
      }
    }
  }
}
</style>
